<template>
  <div class="dashboard-container">
    <div class="app-container">
      <page-tools>
        <!-- 左侧区域 -->
        <template #slot-left>
          <span>共 19 条记录</span>
        </template>
        <!-- 右侧区域 -->
        <template #slot-right>
          <el-button type="danger" size="small" @click="$router.push('/excel')">导入excel</el-button>
          <el-button type="success" size="small" @click="handleDownload">导出excel</el-button>
          <el-button type="primary" size="small" @click="showDialog = true">新增员工</el-button>
        </template>
      </page-tools>
      <!-- 底部卡片 -->
      <el-card class="box-card">
        <!-- 表格部分 -->
        <el-table border :data="employeeList" :default-sort="{prop: 'mobile'}">
          <el-table-column label="序号" type="index" />
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="头像" prop="staffPhoto">
            <template v-slot="scope">
              <image-holder :src="scope.row.staffPhoto" class="staffPhoto" />
            </template>
          </el-table-column>
          <el-table-column label="手机号" prop="mobile" sortable />
          <el-table-column label="工号" prop="workNumber" sortable />
          <el-table-column label="聘用形式" prop="formOfEmployment" :formatter="formatter" />
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column label="入职时间" prop="timeOfEntry">
            <template v-slot="scope">
              <span>{{ scope.row.timeOfEntry | formatTime }}</span>
            </template>
          </el-table-column>
          <el-table-column label="转正时间" prop="correctionTime">
            <template v-slot="scope">
              <span>{{ scope.row.correctionTime | formatTime }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="280">
            <template v-slot="scope">
              <el-button type="text" size="small" @click="$router.push('/employees/detail?id=' + scope.row.id)">查看</el-button>
              <el-button type="text" size="small">分配角色</el-button>
              <el-button type="text" size="small" @click="delEmp(scope.row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页部分 -->
        <el-pagination
          :current-page="query.page"
          :page-sizes="[10, 15, 20, 30]"
          :page-size="query.size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </el-card>
      <!-- 新增弹框 -->
      <el-dialog
        title="新增员工"
        :visible.sync="showDialog"
        width="50%"
        @close="dialogClose"
      >
        <emp-dialog ref="addEmpt" @close="showDialog = false" @updata-list="updataList" />
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { getEmployeeList, delEmployee } from '@/api/employees'
import EmployeeEnum from '@/constant/employees'
import EmpDialog from './empDialog.vue'
import dayjs from 'dayjs'
export default {
  components: { EmpDialog },
  // 过滤器
  filters: {
    formatTime(value) {
      return dayjs(value).format('YYYY-MM-DD')
    }
  },
  data() {
    return {
      query: {
        page: 1,
        size: 10
      },
      total: 0,
      employeeList: [],
      showDialog: false
    }
  },
  created() {
    this.getEmployeeList()
  },
  methods: {
    // 获取员工列表
    async getEmployeeList() {
      const res = await getEmployeeList(this.query)
      this.employeeList = res.data.rows
      this.total = res.data.total
    },

    // 每页显示的条数发生改变时触发
    handleSizeChange(newSize) {
      this.query.size = newSize
      this.getEmployeeList()
    },

    // 当前页面发生改变时触发
    handleCurrentChange(newPage) {
      this.query.page = newPage
      this.getEmployeeList()
    },

    // 格式化聘用形式
    formatter(row, column, cellValue, index) {
      // 通过id查找元素,返回value值
      const obj = EmployeeEnum.hireType.find(item => item.id === cellValue)
      return obj ? obj.value : '未知'
    },

    // 删除员工
    async delEmp(id) {
      const confirmRes = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      // 取消删除
      if (confirmRes === 'cancel') return this.$message('你取消了删除')
      // 确认删除,调用接口
      const res = await delEmployee(id)
      if (this.employeeList.length === 1) {
        this.query.page--
        if (this.query.page === 0) {
          this.query.page = 1
        }
      }
      // 给用户提示
      this.$message.success(res.message)
      // 刷新页面
      this.getEmployeeList()
    },

    // 新增员工
    updataList() {
      // 关闭弹框
      this.showDialog = false
      // 重新渲染页面
      this.getEmployeeList()
    },

    // 新增弹窗关闭时
    dialogClose() {
      this.$refs.addEmpt.resetForm()
    },

    // 格式化导出数据
    transData(rows) {
      // 写代码
      const map = {
        'id': '编号',
        'password': '密码',
        'mobile': '手机号',
        'username': '姓名',
        'timeOfEntry': '入职日期',
        'formOfEmployment': '聘用形式',
        'correctionTime': '转正日期',
        'workNumber': '工号',
        'departmentName': '部门',
        'staffPhoto': '头像地址'
      }
      // 获取英文key
      const headerKeys = Object.keys(rows[0])
      // 通过英文key获取中文key,表头数据
      const header = headerKeys.map(item => {
        return map[item]
      })
      // 获取每条数据的key的值, 具体数据
      const data = rows.map(obj => {
        return Object.values(obj)
      })
      return { header, data }
    },

    // 导出excel
    async handleDownload() {
      const res = await getEmployeeList()
      const excelObj = this.transData(res.data.rows)
      import('@/vendor/Export2Excel').then(excel => {
        console.log(excel)
        const header = excelObj.header
        const data = excelObj.data
        excel.export_json_to_excel({
          header, // 表头 必填
          data, // 具体数据 必填
          filename: '员工信息', // 文件名字
          autoWidth: true, // 是否自适应
          bookType: 'xlsx' // 文件格式
        })
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.box-card {
  margin-top: 10px;
}
.el-pagination {
  margin-top: 10px;
  display: flex;
  justify-content: center;
}
.staffPhoto {
  width: 100px;
  height: 100px;
  border-radius: 50%;
}
</style>
